﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO.IsolatedStorage;
using System.IO;
using DBDataContext.Model;
using WolfGuy;

namespace MangaForYou.Class
{
    public class ISHelper
    {
        public static void WorkWithZipFile(string requestTag)
        {
            try
            {
                using (IsolatedStorageFile isofile = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    //SharpGIS.UnZipper unzip = new SharpGIS.UnZipper(new IsolatedStorageFileStream(
                    //    request.DownloadLocation.ToString(), FileMode.Open, isofile));
                    
                    string strFileType = "";
                    string strImageFileName = "";

                    //string tag = requestTag.Substring(requestTag.LastIndexOf("/"));
                    string[] param = requestTag.Split('@');

                    // param[0] = chapterId
                    // param[1] = manga name
                    // param[2] = chapter file (Ex: Chapter_001.zip)

                    int chapterId = int.Parse(param[0]);
                    string mangaName = param[1];
                    string chapterFolder = param[2].Substring(0, param[2].LastIndexOf("."));

                    string path = String.Format("Shared/Download/{0}/{1}", mangaName, chapterFolder);

                    // Create folder for manga if it's not exist
                    if (!isofile.DirectoryExists("Shared/Download/" + mangaName))
                    {
                        isofile.CreateDirectory("Shared/Download/" + mangaName);
                    }
                    // Create forder for chapter if it's not exist
                    if (!isofile.DirectoryExists(path))
                    {
                        isofile.CreateDirectory(path);
                        isofile.CreateDirectory(string.Format("{0}/Resource", path));
                    }

                    #region "Unzip"
                    // "shared/transfers/"
                    string strDownloadLocation = String.Format("Shared/Transfers/{0}", requestTag);
                    SharpGIS.UnZipper unzip = new SharpGIS.UnZipper(new IsolatedStorageFileStream(
                        strDownloadLocation, FileMode.Open, isofile));

                    foreach (string fileName in unzip.FileNamesInZip)
                    {
                        try
                        {
                            // get file type from file name
                            strFileType = fileName.Substring(fileName.LastIndexOf(".") + 1);

                            // Get stream from file.
                            Stream stream = unzip.GetFileStream(fileName);

                            // if this is htm file, save as htm to isolated storage
                            if (strFileType == "htm")
                            {
                                try
                                {

                                    // Read this stream by streamreader
                                    StreamReader reader = new StreamReader(stream);

                                    string content = reader.ReadToEnd();

                                    // write content to file
                                    // declare stream write.
                                    StreamWriter writer = new StreamWriter(new IsolatedStorageFileStream(
                                        string.Format("{0}/{1}", path, fileName), FileMode.CreateNew, isofile));
                                    writer.Write(content);
                                    writer.Close();
                                }
                                catch (Exception ex)
                                {
                                    //MessageBox.Show("Error happened when application tried to write htm file. " + ex.Message);
                                }
                            }
                            else if (strFileType == "jpg" || strFileType == "png")
                            {
                                try
                                {
                                    strImageFileName = fileName.Substring(fileName.LastIndexOf("/") + 1);

                                    // Create file.
                                    IsolatedStorageFileStream isfs = isofile.CreateFile(
                                        string.Format("{0}/Resource/{1}", path, strImageFileName));

                                    //Using MemoryStream to prevent OutOfMemoryException
                                    byte[] data;
                                    data = new byte[stream.Length];
                                    stream.Read(data, 0, data.Length);

                                    //MemoryStream memorystream = new MemoryStream(data);

                                    //BitmapImage image = new BitmapImage();
                                    //image.SetSource(memorystream);

                                    //WriteableBitmap wb = new WriteableBitmap(image);

                                    //// encode WriteableBitmap object to a JPEG format.
                                    //Extensions.SaveJpeg(wb, isfs, wb.PixelWidth, wb.PixelHeight, 0, 50);

                                    //// Write bitmap file by using BitmapImage and WriteableBitmap
                                    //BitmapImage bitmap = new BitmapImage();
                                    //bitmap.SetSource(stream);

                                    isfs.Write(data, 0, data.Length);
                                    isfs.Flush();
                                    isfs.Close();
                                }
                                catch (OutOfMemoryException ex)
                                {
                                    MessageBox.Show("There is not enough memory to unzip file. Delete chapter and download again.");
                                }
                                catch (Exception ex)
                                {
                                    //MessageBox.Show("Error happened when application tried to write bitmap. " + ex.Message);
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            //MessageBox.Show("Error happened when application tried unzip dowloaded zip file. " + ex.Message);
                        }
                    }// end of foreach
                    #endregion

                    isofile.Dispose();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

}
